import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Upload,
  Tree,
  TreeSelect,
  Modal,
} from "antd";
import {
  PlusOutlined,
  ExclamationCircleFilled,
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
  EditOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  key_find_check_value,
  box_type_list,
} from "../../utils";

export default function Brand(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { Option } = Select;
  const { confirm } = Modal;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [data_list, setData_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("brand", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setData_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("system_manager.number"),
      dataIndex: "brand_number",
      align: "center",
    },
    {
      title: t("system_manager.name"),
      dataIndex: "brand_name",
      align: "center",
    },
    {
      title: t("system_manager.company"),
      dataIndex: "company",
      align: "center",
    },
  ];

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.id);
    setclickRow(row);
  };

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);
    getData();
  };

  const [edit_brand_show, setEdit_brand_show] = useState(false);
  const [edit_user_title, setEdit_user_title] = useState();
  const [edit_type, setEdit_type] = useState("add");

  const [brand_name, setBrand_name] = useState("");
  const [brand_number, setBrand_number] = useState("");
  const edit_brand_dialog_show = (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEdit_user_title(t("common.add"));
      setBrand_name("");
      setBrand_number("");

      setEdit_brand_show(true);
    } else {
      setEdit_brand_show(true);
    }
  };
  const edit_user_confirm = async () => {
    if (brand_name === "") {
      message.warning({
        content: "请输入品牌",
      });
      return;
    }
    if (brand_number === "") {
      message.warning({
        content: "请选择编码",
      });
      return;
    }

    let upMsg = {
      username,
      brand_name,
      brand_number,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type === "change") {
      action = "m_modify";
    }
    setSpinning(true);
    let res = await post_axios("brand", action, upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.successfully"),
    });
    setEdit_brand_show(false);
    search_data();
  };

  const delete_brand = () => {
    if (clickRowKey === "") {
      message.warning({
        content: t("system_manager.choose_one_user"),
      });
      return;
    }
    let { id, brand_name, brand_number } = clickRow;
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          {t("system_manager.sure_to_delete")}
          {t("system_manager.brand")} <strong> {brand_name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          id,
          brand_name,
          brand_number,
          company_id: local_company_object.value.id,
          company: local_company_object.value.company,
        };
        let res = await post_axios("brand", "m_del", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("brand")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 30;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="brand modules">
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_brand_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_brand_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_brand}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={data_list}
              size="small"
              bordered
              columns={columns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title={edit_user_title}
        open={edit_brand_show}
        onOk={edit_user_confirm}
        onCancel={() => setEdit_brand_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">品牌</div>
          <Input
            placeholder=" "
            size="small"
            value={brand_name}
            onChange={(e) => setBrand_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">编码</div>
          <Input
            placeholder=" "
            size="small"
            value={brand_number}
            onChange={(e) => setBrand_number(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
